package view;

import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.filechooser.FileNameExtensionFilter;

import dao.MenuDao;
import modle.Country;
import modle.Menu;
import util.DbUtil;

public class AddMenu extends JFrame {

	private JPanel contentPane;
	private JTextField Name;
	private JTextField Id;
	private JTextField Price;
	private JTextField Description;
	private JTextField Picture;
	private JLabel poi_Label;
	private JLabel id_Label;
	private JLabel up_Label;
	private JLabel ioi_Label;
	private JLabel noi_Label;
	private JLabel addLabel;
	private JButton btnAdd;
	private JComboBox comboBox;
	private List<Country> listCountries;
	private Locale locale;
	ResourceBundle rd;
	MenuDao menuDao = new MenuDao();
	DbUtil dbUtil = new DbUtil();
	private JLabel label_1;
	private JLabel Img;
	private JButton btnFile;
	private String path="";
	private JLabel backgroundlabel;
	private JButton btnBack;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					AddMenu frame = new AddMenu();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public AddMenu() {
		setIconImage(Toolkit.getDefaultToolkit().getImage(AddMenu.class.getResource("/img/iconImage.jpg")));
		setTitle("Welcome to Food Corner");
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setBounds(100, 100, 652, 614);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		
		
		addLabel = new JLabel("Add New Item in Menu", JLabel.CENTER);
		addLabel.setForeground(new Color(205, 133, 63));
		addLabel.setFont(new Font("Microsoft YaHei UI", Font.BOLD, 23));
		addLabel.setBounds(169, 24, 301, 38);
		contentPane.add(addLabel);
		
		Name = new JTextField();
		Name.setBounds(246, 111, 224, 33);
		contentPane.add(Name);
		Name.setColumns(10);
		
		noi_Label = new JLabel("Name of Item: ");
		noi_Label.setForeground(new Color(70, 130, 180));
		noi_Label.setFont(new Font("Microsoft YaHei UI", Font.BOLD, 21));
		noi_Label.setBounds(24, 111, 208, 33);
		contentPane.add(noi_Label);
		
		Id = new JTextField();
		Id.setColumns(10);
		Id.setBounds(246, 170, 224, 33);
		contentPane.add(Id);
		
		Price = new JTextField();
		Price.setColumns(10);
		Price.setBounds(246, 236, 224, 33);
		contentPane.add(Price);
		
		Description = new JTextField();
		Description.setColumns(10);
		Description.setBounds(246, 302, 224, 33);
		contentPane.add(Description);
		
		Picture = new JTextField();
		Picture.setColumns(10);
		Picture.setBounds(246, 367, 224, 33);
		contentPane.add(Picture);
		
		poi_Label = new JLabel("Price of Item: ");
		poi_Label.setForeground(new Color(70, 130, 180));
		poi_Label.setFont(new Font("Microsoft YaHei UI", Font.BOLD, 21));
		poi_Label.setBounds(24, 236, 208, 33);
		contentPane.add(poi_Label);
		
		id_Label = new JLabel("Item Description:");
		id_Label.setForeground(new Color(70, 130, 180));
		id_Label.setFont(new Font("Microsoft YaHei UI", Font.BOLD, 21));
		id_Label.setBounds(24, 302, 224, 33);
		contentPane.add(id_Label);
		
		up_Label = new JLabel("Upload Picture:");
		up_Label.setForeground(new Color(0, 0, 205));
		up_Label.setFont(new Font("Microsoft YaHei UI", Font.BOLD, 21));
		up_Label.setBounds(24, 367, 208, 33);
		contentPane.add(up_Label);
		
		ioi_Label = new JLabel("ID of Item: ");
		ioi_Label.setForeground(new Color(70, 130, 180));
		ioi_Label.setFont(new Font("Microsoft YaHei UI", Font.BOLD, 21));
		ioi_Label.setBounds(24, 170, 208, 33);
		contentPane.add(ioi_Label);
		
		btnAdd = new JButton("Add");
		btnAdd.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 23));
		btnAdd.setBounds(258, 458, 140, 38);
		contentPane.add(btnAdd);
		btnAdd.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				System.out.println("正在向数据库中插入菜单信息");
				addActionPerformed(e);
			}
		});
		
		label_1 = new JLabel("");
		label_1.setIcon(new ImageIcon(AddMenu.class.getResource("/img/admin2.png")));
		label_1.setBounds(514, 140, 75, 98);
		contentPane.add(label_1);
		
		Img = new JLabel("");
		Img.setBounds(412, 413, 208, 142);
		contentPane.add(Img);
		
		btnFile = new JButton("File");
		btnFile.setFont(new Font("Microsoft YaHei UI", Font.BOLD, 17));
		btnFile.setBounds(470, 367, 78, 33);
		contentPane.add(btnFile);
		btnFile.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				updateimg();
			}
		});
		
		comboBox = new JComboBox<>();						//组合按钮或可编辑字段和下拉列表的组件
		comboBox.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 17));
		comboBox.addItemListener(new ItemListener() {		//用于接收项目事件的侦听器接口。
			public void itemStateChanged(ItemEvent e) {
				int index = comboBox.getSelectedIndex();	//返回列表中与给定项目匹配的第一个项目。 
					String arr[] = listCountries.get(index).getId().split("-");					//  ???（应该是遇见 - 就分割）
					locale = new Locale(arr[0], arr[1]);//	???   Locale对象代表具体的地理，政治或文化地区。（第一个是语言，第二个是国家）
					rd = ResourceBundle.getBundle("resources.content", locale);		//使用指定的基本名称，区域设置和类加载器获取资源包（这里好像没用类加载器）。 
					
					//rd到底有什么用
					
					try {
						changeLanguage();
					} catch (Exception e1) {
						e1.printStackTrace();
					}
			}
		});
		comboBox.setBounds(514, 13, 98, 32);
		contentPane.add(comboBox);
		
		btnBack = new JButton("Back");
		btnBack.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 19));
		btnBack.setBounds(14, 506, 98, 38);
		contentPane.add(btnBack);
		btnBack.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				new Admin_Menu().setVisible(true);
				dispose();
			}
		});
		
		fillCountries();
		
	}
	
	//查找图片的绝对路径
		protected void updateimg() {
			// TODO Auto-generated method stub
			
			JFileChooser file = new JFileChooser();
	        file.setCurrentDirectory(new File(System.getProperty("user.home")));
	        //filter the files
	        FileNameExtensionFilter filter = new FileNameExtensionFilter("*.Images", "jpg","gif","png");	//什么意思，有什么用？？
	        //创建具有 FileNameExtensionFilter的说明和文件扩展名的FileNameExtensionFilter。
	        file.addChoosableFileFilter(filter);
	        int result = file.showSaveDialog(null);
	        //if the user click on save in Jfilechooser
	        if(result == JFileChooser.APPROVE_OPTION){
	            File selectedFile = file.getSelectedFile();
	            path = selectedFile.getAbsolutePath();
//	            String s = selectedFile.getPath();
//	            path = selectedFile.getPath();
	            System.out.println(path);
//	            System.out.println(s);
	            Picture.setText(path);
	            Img.setIcon(ResizeImage(path, Img));
	        }
	         //if the user click on save in Jfilechooser
	        else if(result == JFileChooser.CANCEL_OPTION){
	            System.out.println("No File Select");
	        }
		}
		
		private ImageIcon ResizeImage(String imgpath, JLabel label) {
			// TODO Auto-generated method stub
			ImageIcon img1 = new ImageIcon(imgpath);
			Image img2 = img1.getImage();
			Image img3 = img2.getScaledInstance(label.getWidth(), label.getHeight(), Image.SCALE_SMOOTH);
			ImageIcon img4 = new ImageIcon(img3);
			return img4;
		}

	protected void addActionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		String name = Name.getText();
		String id = Id.getText();
		String price = Price.getText();
		String description = Description.getText();
		String picture = Picture.getText();
		
		if (util.StringUtil.isEmpty(name)) {
			JOptionPane.showMessageDialog(null, "name不能为空");
			return;
		}
		if (util.StringUtil.isEmpty(id)) {
			JOptionPane.showMessageDialog(null, "id不能为空");
			return;
		}
		if (util.StringUtil.isEmpty(price)) {
			JOptionPane.showMessageDialog(null, "price不能为空");
			return;
		}
		if (util.StringUtil.isEmpty(description)) {
			JOptionPane.showMessageDialog(null, "description不能为空");
			return;
		}
		
		Menu menu = new Menu(name, id, price, description, picture);
		Connection con = null;
		
		//连接数据库，将菜品信息上传到数据库
		try{
			con = dbUtil.getCon();
			int num = menuDao.MenuAdd(con, menu);
			if(num>0) {
				//弹出提示信息
				JOptionPane.showMessageDialog(null, "菜品添加成功");
//				this.dispose();
			}else {
				//弹出提示信息
				JOptionPane.showMessageDialog(null, "不存在该菜品");
			}
		}catch(Exception e1){
			JOptionPane.showMessageDialog(null, "出现异常，菜品添加失败！");
			e1.printStackTrace();
		}finally {
			try {
				// 关闭数据库连接
				dbUtil.closeCon(con);
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}
	}
	
	private void fillCountries() {
		// TODO Auto-generated method stub
		listCountries = new ArrayList<Country>();
		listCountries.add(new Country("en-US", "English"));
		listCountries.add(new Country("zh-CN", "中文"));
		
		for(Country c : listCountries)
			comboBox.addItem(c.getName());
	}

	protected void changeLanguage() {
		// TODO Auto-generated method stub
		
		ioi_Label.setText(rd.getString("ioi_Label"));
		poi_Label.setText(rd.getString("poi_Label"));
		noi_Label.setText(rd.getString("noi_Label"));
		addLabel.setText(rd.getString("addLabel"));
		id_Label.setText(rd.getString("id_Label"));
		up_Label.setText(rd.getString("up_Label"));
		btnAdd.setText(rd.getString("btnAdd"));
		btnFile.setText(rd.getString("btnFile"));
		btnBack.setText(rd.getString("btnBack"));
	}
}
